<template>
  <div class="edite">
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="100"
    >
      <!-- 参数编码 -->
      <Form-item prop="code" :label="$t('module.configManage.parameterCode')">
        <Input
          v-model.trim="modelForm.code"
          :placeholder="$t('module.configManage.enterparameterCode')"
          :maxlength="50"
          :disabled="configInfo.id != undefined"
        />
      </Form-item>
      <!-- 参数名称 -->
      <Form-item prop="name" :label="$t('module.configManage.parameterName')">
        <Input
          :placeholder="$t('module.configManage.enterparameterName')"
          v-model.trim="modelForm.name"
          :maxlength="50"
        />
      </Form-item>
      <!-- 所属应用 -->
      <Form-item
        prop="applicationCode"
        :label="$t('module.configManage.application')"
        class="application"
      >
        <Select
          :placeholder="$t('module.configManage.selectApplication')"
          v-model="modelForm.applicationCode"
          filterable
          transfer
        >
          <Option
            v-for="app in appList"
            :value="app.clientId"
            :key="app.clientId"
            :style="{ color:app.enabled == 0?'#bcbcbc': '' }"
            :label="app.appName"
          ></Option>
        </Select>
      </Form-item>
      <!--值来源  -->
      <Form-item :label="$t('module.configManage.sourceValue')">
        <Row :gutter="32">
          <Col span="20">
            <Input
              v-model="modelForm.valueSetName"
              disabled
              :placeholder="$t('module.configManage.selectSourceValue')"
            ></Input>
          </Col>
          <Col span="4" class="textLeft">
            <RPButton
              optType="reset"
              :text="$t('module.configManage.select')"
              style="borderRadius:0;"
              @click="selectparameterSource"
            />
          </Col>
        </Row>
        <!-- <RPButton
          optType="reset"
          :text="$t('module.configManage.select')"
          @click="selectparameterSource"
          :disabled="isParameterDisabled"
          style="borderRadius:0;marginLeft:10px;"
        />-->
      </Form-item>
      <!-- 默认值 -->
      <Form-item v-if="isShowInput" prop :label="$t('module.configManage.defaultValue')">
        <Input
          :placeholder="$t('module.configManage.enterDefaultValue')"
          v-model="modelForm.defaultValue"
          :maxlength="50"
        />
      </Form-item>
      <Form-item
        v-show="isShowSelect"
        prop="defaultValue"
        :label="$t('module.configManage.defaultValue')"
      >
        <Select
          :placeholder="$t('module.configManage.selectDefaultValue')"
          v-model="modelForm.defaultValue"
          clearable
          @on-change="selectDefaultValue"
        >
          <Option
            v-for="item in valueItemList"
            :value="item.vsiKey"
            :key="item.vsiKey"
          >{{item.vsiValue}}</Option>
        </Select>
      </Form-item>
      <!-- 状态 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled">
              <Radio :label="1">{{ $t("common.enable") }}</Radio>
              <Radio :label="0">{{ $t("common.disable") }}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- 描述 -->
      <Form-item :label="$t('module.configManage.description')">
        <Input
          v-model="modelForm.description"
          type="textarea"
          :rows="4"
          placeholder
          :maxlength="200"
        />
      </Form-item>
    </Form>
  </div>
</template>
<script>
import { addConfig, updateConfig } from "@/api/configApi.js";
import locales from "./locales.js";
import SelectValueSet from "./SelectValueSet.vue";
import valueSetAPI from "@/api/valueSetAPI.js";
import { getOwnedApplicationByTenantCode } from "@/api/applicationApi";
import { codeReg } from "@/const.js";

export default {
  name: "editeConfig",
  mixins: [locales],
  props: {
    tenantCode: {
      type: String,
      default: ""
    },
    configInfo: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const validateConfigCode = (rule, value, callback) => {
      if (value === "" || value === undefined || value === null) {
        callback(new Error(this.$t("module.configManage.enterparameterCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };

    const validateDefaultValue = (rule, value, callback) => {
      if (!this.isShowSelect) {
        callback();
      } else if (this.isShowSelect && !value) {
        callback(new Error(this.$t("module.configManage.setDefaultValue")));
      }
      callback();
    };

    return {
      modelForm: {
        tenantCode: this.tenantCode,
        id: "",
        name: "",
        code: "",
        description: "",
        enabled: 1,
        version: 0,
        createTime: "",
        createUserId: "",
        deleted: "",
        updateTime: "",
        valueSetCode: "",
        valueSetName: "", //值来源
        applicationCode: "", //所属应用
        valueSetId: "", //配置项值集id
        defaultValue: "", //默认值
        defaultValueVsiId: "" //配置项值集的值id
      },
      valueSetName: "",
      isShowInput: true,
      isShowSelect: false,
      defaultValueName: "",
      valueItemList: [],
      appList: [],
      rule: {
        code: [{ validator: validateConfigCode, trigger: "blur", required: true }],
        name: [
          {
            required: true,
            message: this.$t("module.configManage.enterparameterName"),
            trigger: "blur"
          }
        ],
        applicationCode: [
          {
            required: true,
            message: this.$t("module.configManage.selectApplication"),
            trigger: "change"
          }
        ],
        defaultValue: [
          {
            required: true,
            validator: validateDefaultValue,
            trigger: "change"
          }
        ]
      },
      isParameterDisabled:
        this.tenantCode != window.RPConfig.rootTenantCode &&
        this.configInfo.tenantCode &&
        this.configInfo.tenantCode != this.tenantCode,
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  watch: {
    configInfo: {
      handler: function(val) {
        this.modelForm = Object.assign({}, this.modelForm, val);
        if (val.valueSetName) this.modelForm.valueSetName = val.valueSetName + ' (' + val.valueSetCode + ')';
      },
      immediate: true
    }
  },
  created() {
    this.init();
    this.initApplication();
  },
  methods: {
    selectDefaultValue(value) {
      this.valueItemList.map(item => {
        if (item.vsiKey == value) {
          this.modelForm.defaultValueVsiId = item.id;
        }
      });
    },
    init() {
      if (this.configInfo.id) {
        this.isShowInput = false;
        this.isShowSelect = false;
        this.$emit("SetTitle", this.$t("module.configManage.editConfig"));
      } else {
        this.$emit("SetTitle", this.$t("module.configManage.createConfig"));
      }
      // 调整宽度
      this.$emit("SetPageWidth", 700);
      this.$emit("SetPageActions", this.actions);
    },
    //初始化所属自建应用
    initApplication() {
      getOwnedApplicationByTenantCode({ tenantCode: this.tenantCode, isOwned: true }).then(res => {
        this.appList = res.data;
      });
    },

    // 选择参数值来源
    selectparameterSource() {
      new this.$pageModal(
        SelectValueSet,
        {
          props: {
            // tenantCode: "0000"
            // tenantCode: this.tenantCode
            paramInfo: this.configInfo
          }
        },
        data => {
          valueSetAPI.getValueSetByCode(data.vsCode).then(data => {
            this.valueItemList = data;
          });
          if (data) {
            this.modelForm.valueSetId = data.id;
            this.modelForm.valueSetName = data.vsName + ' (' + data.vsCode + ')';
            if (!this.configInfo.id) {
              if (this.modelForm.valueSetName) {
                this.isShowSelect = true;
                this.isShowInput = false;
              } else {
                this.isShowInput = false;
                this.isShowSelect = true;
              }
            }

            this.modelForm.valueSetCode = data.vsCode;
          }
        }
      );
    },
    // 保存修改后的信息
    save() {
      this.$refs["editForm"].validate(valid => {
        //   验证参数
        if (valid) {
          this.actions[0].loading = true;
          const { modelForm, configInfo } = this;
          //   请求接口保存
          if (configInfo.id) {
            updateConfig(modelForm)
              .then(res => {
                if (res) {
                  const content = this.$t("module.receiptSequence.updateSuccess");
                  this.$message.success({
                    content: content,
                    duration: 3
                  });
                  this.$emit("Close", true);
                  return;
                }
                this.$message.error({
                  content: this.$t("module.receiptSequence.saveFailed"),
                  duration: 3
                });
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          } else {
            addConfig(modelForm)
              .then(res => {
                if (res) {
                  // const content = configInfo.id
                  //   ? this.$t("module.receiptSequence.editSuccess")
                  //   : this.$t("module.receiptSequence.createSuccess");
                  const content = this.$t("module.receiptSequence.createSuccess");
                  this.$message.success({
                    content: content,
                    duration: 3
                  });
                  this.$emit("Close", true);
                  return;
                }
                this.$message.error({
                  content: this.$t("module.receiptSequence.saveFailed"),
                  duration: 3
                });
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          }

          return;
        }
        this.$message.error({
          content: this.$t("common.formValidateFailed"),
          duration: 3
        });
        return 0;
      });
    }
  }
};
</script>
<style lang="less">
.edite {
  .textLeft {
    text-align: right;
    min-width: auto !important;
  }
}
</style>
